package com.king.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIO 案例演示
 * 通过 telnet 命令进行测试。
 * Ctrl + ]：进入发送窗口
 * send：发送命令，后面加上内容
 *
 * @author king
 * @date 2020/12/22 21:38
 */
public class BioServer {
    public static void main(String[] args) throws IOException {
        // 线程池机制

        // 思路
        // 1. 创建一个线程池
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        // 2. 如果有客户端连接，就创建一个线程，与之通信
        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println("服务器启动");

        while (true) {
            // 监听，等待客户端连接
            System.out.println("等待连接...");
            final Socket socket = serverSocket.accept();
            System.out.println("客户端连接");

            // 创建一个线程与之通信
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);
                }
            });
        }

    }

    /**
     * 和客户端通信
     *
     * @param socket
     */
    public static void handler(Socket socket) {
        System.out.println("线程信息 id=" + Thread.currentThread().getId());
        byte[] bytes = new byte[1024];
        try {
            // 通过 socket 获取输入流
            InputStream inputStream = socket.getInputStream();

            // 循环的读取客户端发送的数据
            while (true) {
                System.out.println("线程信息 name=" + Thread.currentThread().getName());
                System.out.println("read...");
                int read = inputStream.read(bytes);
                if (read != -1) {
                    // 输出客户端发送的数据
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
